package com.yang.utils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class AddTextToImg {
    public static void main(String[] args) {
        String filePath = "./tps3.png";
        String outPath = "./tps3_text.png";
        String text = "00:00:00    00:00:30    00:01:00    00:01:30    00:02:00    00:02:30    00:03:00    00:03:30    00:04:00    00:04:30    00:05:00";
        drawTextInImg(filePath, text, outPath, 100, 446, 12.0f);
    }

    public static void drawTextInImg(String filePath, String text, String outPath, int left_n, int top_n, float font_size){
        ImageIcon imageIcon = new ImageIcon(filePath);
        Image image = imageIcon.getImage();
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

        Graphics2D g = bufferedImage.createGraphics();

        int fontSize = (int) font_size;
        int rectX = left_n;
        int rectY = top_n;
        int rectWidth = text.length() * (fontSize + 30);
        int rectHeight = fontSize + 8;

        Font font = new Font("宋体", Font.PLAIN, fontSize);
        g.setBackground(Color.white);
        g.drawImage(image, 0,0,null);
        g.setPaint(new Color(67, 67, 72));

        g.setFont(font);
        g.drawString(text, rectX, top_n);
        g.dispose();

        try {
            FileOutputStream out = new FileOutputStream(outPath);
            ImageIO.write(bufferedImage, "png", out);
            out.close();
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}
